<template>
      <!-- 页面头部 -->
      <div class="header-section">
        <div class="header-content">
          <div class="title-section">
            <h2 class="page-title">
              <i class="el-icon-thumb"></i> 跟团游审核列表
            </h2>
            <p class="page-subtitle">管理跟团游相关信息</p>
          </div>
          <div class="total-count">
            <div class="count-card">
              <span class="count-label">跟团游总数</span>
              <span class="count-value">{{ total }}</span>
            </div>
          </div>
        </div>
      </div>

      <!-- 精简后的筛选栏 -->
      <div class="filter-container">
        <div class="filter-row">
          <el-form-item label="跟团游名称" class="filter-item">
            <el-input
              v-model="filterParams.groupTourName"
              placeholder="请输入跟团游名称"
              clearable
              class="filter-input"
            />
          </el-form-item>
          <el-form-item label="旅行社名称" class="filter-item">
            <el-input
              v-model="filterParams.travelAgencyName"
              placeholder="请输入旅行社名称"
              clearable
              class="filter-input"
            />
          </el-form-item>
          <el-form-item label="审核状态" class="filter-item">
            <el-select
              v-model="filterParams.auditStatus"
              placeholder="请选择状态"
              clearable
              class="filter-select"
            >
              <el-option label="通过" value="通过" />
              <el-option label="未通过" value="未通过" />
              <el-option label="未审核" value="未审核" />
            </el-select>
          </el-form-item>
        </div>
        <div class="button-row" style="display: flex; justify-content: flex-end; gap: 15px; padding-top: 10px; border-top: 1px solid #ebeef5; margin-top: 10px;">
          <el-button 
            type="primary" 
            @click="handleFilter"
          >
            筛选
          </el-button>
          <el-button 
            @click="resetFilter"
          >
            重置
          </el-button>
          <el-button 
            type="danger" 
            @click="handleBatchDelete"
            :disabled="selectedItems.length === 0"
          >
            批量删除
          </el-button>
        </div>
      </div>

      <!-- 数据表格和分页区域 -->
      <div class="table-and-pagination">
        <div class="data-table-card">
          <el-table 
            :data="tableData" 
            class="data-table"
            @selection-change="handleSelectionChange"
            v-loading="loading"
            stripe
            border
            height="100%"
          >
            <el-table-column type="selection" width="55" fixed />
            <el-table-column label="编号" width="120" fixed>
              <template #default="scope">
                {{ getNaturalCode(scope.row.groupTourId) }}
              </template>
            </el-table-column>
            <el-table-column prop="groupTourName" label="跟团游名称" width="180" fixed />
            <el-table-column prop="scenicSpotName" label="景点名称" width="180" />
            <el-table-column prop="travelAgencyName" label="旅行社名称" width="180" />
            <el-table-column prop="auditStatus" label="审核状态" width="120" fixed="right">
              <template #default="{ row }">
                <el-tag :type="getStatusTagType(row.auditStatus)">
                  {{ row.auditStatus }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="startDate" label="开始时间" width="150">
              <template #default="{ row }">
                {{ formatDate(row.startDate) }}
              </template>
            </el-table-column>
            <el-table-column prop="endDate" label="结束时间" width="150">
              <template #default="{ row }">
                {{ formatDate(row.endDate) }}
              </template>
            </el-table-column>
            <el-table-column fixed="right" label="操作" width="180">
              <template #default="scope">
                <el-button 
                  size="small" 
                  type="primary" 
                  @click="handleDetail(scope.row.groupTourId)">
                  详情
                </el-button>
                <el-button 
                  size="small" 
                  class="delete-btn" 
                  @click="handleDelete(scope.row.groupTourId)">
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>

        <!-- 分页组件 -->
        <div class="pagination-wrapper">
          <el-pagination
            v-model:current-page="pagination.currentPage"
            v-model:page-size="pagination.pageSize"
            :page-sizes="[10, 20, 50, 100]"
            :background="true"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Filter, Refresh, Delete, View } from '@element-plus/icons-vue'
import dayjs from 'dayjs'
import axios from 'axios'
import { useRouter } from 'vue-router'

const router = useRouter()
const tableData = ref([])
const loading = ref(false)
const total = ref(0)
const selectedItems = ref([])

// 省份和城市选项数据
const provinceOptions = ref(['北京', '上海', '广东', '江苏', '浙江', '四川', '山东', '福建', '湖南', '湖北'])
const cityOptions = ref(['北京', '上海', '广州', '深圳', '杭州', '成都', '武汉', '南京', '西安', '重庆'])

// 筛选参数
const filterParams = ref({
  groupTourName: '',
  scenicSpotName: '',
  travelAgencyName: '',
  province: '',
  city: '',
  auditStatus: '',
  startDate: '',
  endDate: ''
})

// 分页参数
const pagination = ref({
  currentPage: 1,
  pageSize: 10
})

// 新增：用于缓存groupTourId与自然编号的映射
const idMap = new Map()
function getRandomCode() {
  return 'T' + Math.floor(Math.random() * 100000).toString().padStart(5, '0')
}
function getNaturalCode(groupTourId) {
  if (!idMap.has(groupTourId)) {
    let code
    do {
      code = getRandomCode()
    } while ([...idMap.values()].includes(code))
    idMap.set(groupTourId, code)
  }
  return idMap.get(groupTourId)
}

// 格式化日期显示
const formatDate = (date) => {
  return dayjs(date).format('YYYY-MM-DD')
}

// 获取状态标签类型
const getStatusTagType = (status) => {
  switch (status) {
    case '通过': return 'success'
    case '未通过': return 'danger'
    case '未审核': return 'warning'
    default: return 'info'
  }
}

// 构建请求参数
const buildRequestParams = () => {
  const params = {
    pageNum: pagination.value.currentPage,
    pageSize: pagination.value.pageSize
  }

  // 筛选参数
  if (filterParams.value.groupTourName) {
    params.groupTourName = filterParams.value.groupTourName
  }
  if (filterParams.value.scenicSpotName) {
    params.scenicSpotName = filterParams.value.scenicSpotName
  }
  if (filterParams.value.travelAgencyName) {
    params.travelAgencyName = filterParams.value.travelAgencyName
  }
  if (filterParams.value.province) {
    params.province = filterParams.value.province
  }
  if (filterParams.value.city) {
    params.city = filterParams.value.city
  }
  if (filterParams.value.auditStatus) {
    params.auditStatus = filterParams.value.auditStatus
  }
  if (filterParams.value.startDate) {
    params.startDate = filterParams.value.startDate
  }
  if (filterParams.value.endDate) {
    params.endDate = filterParams.value.endDate
  }

  return params
}

// 获取跟团游列表
const fetchData = async () => {
  try {
    loading.value = true
    const params = buildRequestParams()
    
    const response = await axios.get('/mw/travel/list', { params })
    
    if (response.data) {
      total.value = response.data.total
      tableData.value = response.data.list || []
    } else {
      throw new Error('获取数据失败')
    }
  } catch (error) {
    ElMessage.error('获取跟团游数据失败: ' + (error.response?.data?.message || error.message))
  } finally {
    loading.value = false
  }
}

// 筛选
const handleFilter = () => {
  pagination.value.currentPage = 1
  fetchData()
}

// 重置筛选
const resetFilter = (shouldFetch = true) => {
  filterParams.value = {
    groupTourName: '',
    scenicSpotName: '',
    travelAgencyName: '',
    province: '',
    city: '',
    auditStatus: '',
    startDate: '',
    endDate: ''
  }
  if (shouldFetch) {
    pagination.value.currentPage = 1
    fetchData()
  }
}

// 查看详情
const handleDetail = (id) => {
  router.push({ name: 'TravelAudit', params: { id } })
}

// 删除跟团游
const handleDelete = async (id) => {
  try {
    await ElMessageBox.confirm('确定删除这条跟团游记录吗?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    loading.value = true
    const response = await axios.delete(`/mw/travel/delete/${id}`)
    if (response.data > 0) {
      ElMessage.success('删除成功')
      fetchData()
    } else {
      ElMessage.error('删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败: ' + (error.response?.data?.message || error.message))
    }
  } finally {
    loading.value = false
  }
}

// 批量删除
const handleBatchDelete = async () => {
  try {
    await ElMessageBox.confirm(
      `确定删除选中的${selectedItems.value.length}条跟团游记录吗?`, 
      '提示', 
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    loading.value = true
    const ids = selectedItems.value.map(item => item.groupTourId)
    const response = await axios.post('/mw/travel/batchDelete', { ids })
    
    if (response.data > 0) {
      ElMessage.success(`成功删除${response.data}条记录`)
      fetchData()
      selectedItems.value = []
    } else {
      ElMessage.error('删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('批量删除失败: ' + (error.response?.data?.message || error.message))
    }
  } finally {
    loading.value = false
  }
}

// 选择项变化
const handleSelectionChange = (selection) => {
  selectedItems.value = selection
}

// 分页大小改变
const handleSizeChange = (val) => {
  pagination.value.pageSize = val
  fetchData()
}

// 当前页改变
const handleCurrentChange = (val) => {
  pagination.value.currentPage = val
  fetchData()
}

// 初始化加载数据
onMounted(() => {
  fetchData()
})
</script>

<style scoped>
.app-container {
  padding: 20px;
  min-height: calc(100vh - 40px);
  box-sizing: border-box;
  background-color: #f0f2f5;
  display: flex;
  flex-direction: column;
}

.box-card {
  width: 100%;
  flex: 1;
  display: flex;
  flex-direction: column;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

/* 头部样式保持不变 */
.header-section {
  background: linear-gradient(135deg, #a0c4e4 0%, #7fa8d1 100%);
  padding: 20px 25px;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(160, 196, 228, 0.2);
  margin-bottom: 24px;
  color: #2c3e50;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.title-section {
  .page-title {
    margin: 0;
    font-size: 24px;
    font-weight: 600;
    display: flex;
    align-items: center;
    gap: 10px;
    
    i {
      font-size: 28px;
      color: #2c3e50;
    }
  }
  
  .page-subtitle {
    margin: 5px 0 0;
    font-size: 14px;
    color: #4a5568;
  }
}

.total-count {
  .count-card {
    background: rgba(255, 255, 255, 0.7);
    padding: 12px 20px;
    border-radius: 8px;
    display: flex;
    flex-direction: column;
    align-items: center;
    border: 1px solid #e2e8f0;
    
    .count-label {
      font-size: 14px;
      margin-bottom: 5px;
      color: #4a5568;
    }
    
    .count-value {
      font-size: 24px;
      font-weight: 700;
      color: #2c3e50;
    }
  }
}

.filter-container {
  margin-bottom: 15px;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 4px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);
}

.filter-row {
  display: flex;
  flex-wrap: nowrap;
  margin-bottom: 15px;
  align-items: center;
}

.filter-item {
  margin-right: 25px;
  margin-bottom: 0;
  display: flex;
  align-items: center;
}

.filter-item:last-child {
  margin-right: 0;
}

.button-row {
  display: flex;
  justify-content: flex-start;
  gap: 15px;
  padding-top: 10px;
  border-top: 1px solid #ebeef5;
  margin-top: 10px;
}

.el-form-item__label {
  font-weight: 500;
  color: #606266;
}

/* 修改表格和分页区域样式 */
.table-and-pagination {
  flex: 1;
  display: flex;
  flex-direction: column;
  min-height: 0;
  overflow: hidden;
  
  .data-table-card {
    flex: 1;
    min-height: 0;
    overflow: hidden;
    
    :deep(.el-table) {
      height: calc(100% - 60px) !important;
    }
  }
  
  .pagination-wrapper {
    flex-shrink: 0;
    padding: 16px 0;
    background: white;
    border-top: 1px solid #ebeef5;
    display: flex;
    justify-content: center;
  }
}

/* 响应式调整 */
@media (max-width: 1500px) {
  .filter-row {
    flex-wrap: wrap;
  }
  
  .filter-item {
    margin-right: 15px;
    margin-bottom: 10px;
  }
}

@media (max-width: 1200px) {
  .filter-container {
    padding: 12px;
  }
  
  .filter-item {
    margin-right: 12px;
  }
}

@media (max-width: 768px) {
  .app-container {
    padding: 10px;
  }
  
  .header-content {
    flex-direction: column;
    align-items: flex-start;
    gap: 15px;
  }
  
  .filter-row {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .filter-item {
    width: 100%;
    margin-right: 0;
    margin-bottom: 12px;
  }
  
  .el-select, .el-input, .el-date-picker {
    width: 100% !important;
  }
  
  .button-row {
    width: 100%;
    flex-wrap: wrap;
  }
  
  .data-table {
    font-size: 14px;
  }
}

/* 新增的样式 */
.filter-row {
  display: flex;
  justify-content: space-between;
  margin-bottom: 15px;
  gap: 15px;
}

.filter-item {
  flex: 1;
  min-width: 0;
  margin-bottom: 0;
  display: flex;
  align-items: center;
}

.filter-input,
.filter-select,
.filter-date {
  width: 100%;
}

/* 响应式调整 */
@media (max-width: 1200px) {
  .filter-row {
    flex-wrap: wrap;
  }
  
  .filter-item {
    min-width: calc(50% - 8px);
    flex: none;
  }
}

@media (max-width: 768px) {
  .filter-item {
    min-width: 100%;
  }
  
  .filter-row {
    gap: 12px;
  }
}

.delete-btn {
  background: #fff;
  border: 1px solid #f56c6c;
  color: #f56c6c;
  transition: all 0.2s;
}
.delete-btn:hover {
  background: #f56c6c;
  color: #fff;
  border-color: #f56c6c;
}
</style>